<template>
  <div class="shop-order-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>销售订单管理</h2>
          <el-button type="primary" @click="addShopOrder">新增销售订单</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.shopOrderCode" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单日期">
          <el-date-picker
            v-model="searchForm.shopOrderDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="loading"
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="shopOrderCode" label="销售单号" width="120"></el-table-column>
        <el-table-column prop="shopOrderDate" label="销售日期" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="120"></el-table-column>
        <el-table-column prop="deptName" label="销售部门" width="120"></el-table-column>
        <el-table-column prop="userName" label="销售负责人" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注" width="120"></el-table-column>
        <el-table-column prop="status" label="单据状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shopAllNum" label="销售总数量" width="80"></el-table-column>
        <el-table-column prop="shopAllMoney" label="销售总金额" width="100"></el-table-column>
        <el-table-column prop="shopAllGoods" label="商品描述" min-width="150"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createDate" label="创建日期" width="150"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button type="success" size="small" @click="editShopOrder(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteShopOrder(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

// 路由
const router = useRouter();

// 搜索表单
const searchForm = reactive({
  shopOrderCode: '',
  shopOrderDate: []
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 初始化
onMounted(() => {
  loadData();
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  // 如果日期已经是格式化的，直接返回
  if (dateString.includes('-') && dateString.length >= 10) {
    return dateString.substring(0, 10);
  }
  
  try {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
  } catch (e) {
    return dateString;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '待审批';
    case 2: return '已审批';
    case 3: return '已拒绝';
    default: return '未知状态';
  }
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return ''; // 草稿
    case 1: return 'warning'; // 待审批
    case 2: return 'success'; // 已审批
    case 3: return 'danger'; // 已拒绝
    default: return '';
  }
};

// 加载表格数据
const loadData = () => {
  loading.value = true;
  
  // 构建查询参数
  const params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  };
  
  if (searchForm.shopOrderCode) {
    params.shopOrderCode = searchForm.shopOrderCode;
  }
  
  if (searchForm.shopOrderDate && searchForm.shopOrderDate.length === 2) {
    params.startDate = searchForm.shopOrderDate[0];
    params.endDate = searchForm.shopOrderDate[1];
  }
  
  // 调用后端API
  axios.get(`/api/ShopOrder/pageWithRelations`, { 
    params: params
  })
  .then(response => {
    console.log('API返回数据:', response.data);
    if (response.data && response.data.code === 200) {
      // 将后端返回的数据转换为前端表格需要的格式
      const data = response.data.data || [];
      
      // 处理数据，确保日期格式正确
      tableData.value = data.map(item => {
        // 确保日期格式正确
        if (item.shopOrderDate) {
          item.shopOrderDate = formatDate(item.shopOrderDate);
        }
        if (item.createDate) {
          item.createDate = formatDate(item.createDate);
        }
        
        return item;
      });
      
      total.value = response.data.totalCount || data.length || 0;
    } else {
      ElMessage.error(response.data?.message || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  })
  .catch(error => {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请检查网络连接');
    tableData.value = [];
    total.value = 0;
  })
  .finally(() => {
    loading.value = false;
  });
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = [];
    } else {
      searchForm[key] = '';
    }
  });
  handleSearch();
};

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size;
  loadData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadData();
};

// 新增销售订单
const addShopOrder = () => {
  router.push('/ShopOrderEdit');
};

// 查看详情
const viewDetail = (row) => {
  router.push(`/ShopOrderDetail/${row.id}`);
};

// 编辑销售订单
const editShopOrder = (row) => {
  router.push(`/ShopOrderEdit/${row.id}`);
};

// 删除销售订单
const deleteShopOrder = (row) => {
  ElMessageBox.confirm('确定要删除该销售订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/api/ShopOrder/${row.id}`)
      .then(response => {
        if (response.data && response.data.code === 200) {
          ElMessage.success('删除成功');
          loadData();
        } else {
          ElMessage.error(response.data?.message || '删除失败');
        }
      })
      .catch(error => {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请检查网络连接');
      });
  }).catch(() => {});
};
</script>

<style scoped>
.shop-order-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
